﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using System.Net;
using Microsoft.TeamFoundation;
using System.Diagnostics;
using System.IO;

namespace TestConnectionTFS
{
    class Program
    {
        static void Main(string[] args)
        {
            string userName = "koko_codeplex_cp";
            string password = "tfswants";
            string TfsName = "tfs.codeplex.com";
            string localPath = "D:\\DEMO";
            Workspace workspace = null;

            NetworkCredential creditentials = new NetworkCredential(userName, password);

            // Connect to the team project collection and the server that hosts the version-control repository. 
            TfsTeamProjectCollection tpc =
               new TfsTeamProjectCollection(new Uri(string.Format("https://{0}:443/tfs/TFS36", TfsName)), creditentials);

            try
            {
                tpc.Authenticate();

                VersionControlServer vcServer = tpc.GetService<VersionControlServer>();
                workspace = vcServer.GetWorkspace(localPath);               

                //// Add new Folder
                //AddNewFile(workspace, "D:\\DEMO\\NewFile");                

                //// Delete Folder
                //DeleteFolder(workspace, "D:\\DEMO\\NewFile");              

                //// Modify File               
                //ModifyFile(workspace, "D:\\DEMO\\Animals\\Cat.cs");

                //// List All files
                //ListAllFiles(vcServer);

                var xx = 300;
            }

            #region TeamFoundationServerUnauthorizedException
            catch (Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException ex)
            {
                //Console.WriteLine("Data: ");
                //Console.WriteLine(ex.Data.ToString());
                //Console.WriteLine("HelpLink: ");
                //Console.WriteLine(ex.HelpLink.ToString());
                //Console.WriteLine("IsRemoteException: ");
                //Console.WriteLine(ex.IsRemoteException.ToString());
                //Console.WriteLine("Message: ");
                //Console.WriteLine(ex.Message.ToString());
                //Console.WriteLine("RemoteExceptionCode: ");
                //Console.WriteLine(ex.RemoteExceptionCode.ToString());
                //Console.WriteLine("Source: ");
                //Console.WriteLine(ex.Source.ToString());
                //Console.WriteLine("StackTrace: ");
                //Console.WriteLine(ex.StackTrace.ToString());
                //Console.WriteLine("HelpLink: ");
                //Console.WriteLine(ex.TargetSite.ToString());                
                Console.WriteLine(ex.ToString());
            }
            #endregion // TeamFoundationServerUnauthorizedException
        }

        #region ModifyFile
        private static void ModifyFile(Workspace workspace, String newFilename)
        {
            Debug.Assert(workspace != null);
            Debug.Assert(!String.IsNullOrEmpty(newFilename));

            try
            {
                // Checkout and modify the file
                workspace.PendEdit(newFilename);

                using (var streamWriter = new StreamWriter(newFilename))
                {
                    streamWriter.WriteLine("Revision 2");
                }

                // Get the pending change and check in the new revision.
                var pendingChanges = workspace.GetPendingChanges();
                int changesetForChange = workspace.CheckIn(pendingChanges, "Modified file contents");
                Console.WriteLine("Checked in changeset {0}", changesetForChange);
            }
            catch (IOException ex)
            {
                Console.Error.WriteLine("Error writing {1}: {0}", ex.Message, newFilename);
                throw;
            }
            catch (VersionControlException ex)
            {
                Console.Error.WriteLine("Error modifying file: {0}", ex.Message);
                throw;
            }
        }
        #endregion // ModifyFile

        #region AddNewFile
        private static void AddNewFile(Workspace workspace, String newFilename)
        {
            Debug.Assert(workspace != null);
            Debug.Assert(!String.IsNullOrEmpty(newFilename));
            Debug.Assert(!File.Exists(newFilename));

            if (!workspace.HasCheckInPermission)
            {
                throw new SecurityException(
                    String.Format("{0} does not have check-in permission for workspace: {1}",
                                  workspace.VersionControlServer.AuthorizedUser,
                                  workspace.DisplayName));
            }

            try
            {
                // create the new file
                using (var streamWriter = new StreamWriter(newFilename))
                {
                    streamWriter.WriteLine("Revision 1");
                }

                // Now pend the add of our new folder and file
                workspace.PendAdd(Path.GetDirectoryName(newFilename), true);

                // Show our pending changes
                var pendingAdds = new List<PendingChange>(workspace.GetPendingChanges());

                pendingAdds.ForEach(add => Console.WriteLine("\t{1}: {0}",
                                                             add.LocalItem,
                                                             PendingChange.GetLocalizedStringForChangeType(
                                                                 add.ChangeType)));

                // Checkin the items we added
                int changesetForAdd = workspace.CheckIn(pendingAdds.ToArray(), "Initial check-in");
                Console.WriteLine("Checked in changeset {0}", changesetForAdd);
            }
            catch (IOException ex)
            {
                Console.Error.WriteLine("Error writing {1}: {0}", ex.Message, newFilename);
                throw;
            }
            catch (VersionControlException ex)
            {
                Console.Error.WriteLine("Error adding file: {0}", ex.Message);
                throw;
            }
        }
        #endregion // AddNewFile

        #region ListAllFiles
        private static void ListAllFiles(VersionControlServer vcServer)
        {
            // List all of the files.
            ItemSet items = vcServer.GetItems("$/*.*", RecursionType.Full);
            foreach (Item item in items.Items)
            {
                Console.Write(item.ItemType.ToString());
                Console.Write(": ");
                Console.WriteLine(item.ServerItem.ToString());
            }            
        }
        #endregion // ListAllFiles

        #region DeleteFolder
        private static void DeleteFolder(Workspace workspace, String newFolder)
        {
            Debug.Assert(workspace != null);
            Debug.Assert(!String.IsNullOrEmpty(newFolder));

            try
            {
                // Delete the items
                workspace.PendDelete(workspace.GetServerItemForLocalItem(newFolder), RecursionType.Full);
                var pendingDeletes = workspace.GetPendingChanges();

                if (pendingDeletes.Length > 0)
                {
                    workspace.CheckIn(pendingDeletes, "Clean up!");
                }
            }
            catch (VersionControlException ex)
            {
                Console.Error.WriteLine("Error deleting file: {0}", ex.Message);
                throw;
            }
        }
        #endregion // DeleteFolder
    }
}
